# coding=utf-8

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from model import EgFiles
from flask import request, send_from_directory
import os, time
import hashlib
import json
import random
import string
from config import sysconfig

from flask import Flask
app = Flask(__name__)


engine = create_engine("mysql+mysqlconnector://root:" + sysconfig['db_pwd'] + "@localhost/egfs", encoding='utf-8', echo=False)
Session_class = sessionmaker(bind=engine)

@app.route('/')
def helloworld():
    return "hello World!"


@app.route('/upload', methods=['post'])
def upload():
    session = Session_class()  # 生成session实例 #cursor
    fname = request.files['file']
    if fname:
        try:
            t = time.strftime('%Y%m%d%H%M%S')
            #文件名由 上传时间+随机字符串+文件名组成
            new_fname = r'upload/' + t + '_'+ ''.join(random.sample(string.ascii_letters, 8))+'_' + fname.filename.encode('utf8')
            fname.save(new_fname)
            # Save file to temp folder
            exe_str = '/usr/bin/fdfs_upload_file /etc/fdfs/client.conf ' + new_fname
            # Get file path in FastDFS
            ret = os.popen(exe_str)
            egpath_tmp = ret.read()
            egpath = egpath_tmp[0:len(egpath_tmp)-1]
            # Initiate EgFiles Object
            egfile = EgFiles()
            egfile.uuid = hashlib.md5(egpath.encode('utf-8')).hexdigest()
            uuid = egfile.uuid
            egfile.filename = fname.filename
            egfile.path = egpath
            egfile.created_at = time.strftime('%Y-%m-%d %H:%M:%S')
            session.add(egfile)
            session.commit()
            session.close()
            return json.dumps({'code': 200, 'msg': 'File Upload Success', 'uuid': uuid})
        except Exception, ex:
            session.close()
            print ex
            return json.dumps({'code': 400, 'msg': 'File-upload-failed'})
    else:
        session.close()
        return json.dumps({'code': 400, 'msg': 'File Upload Failed'})


@app.route('/geturl',  methods=['get'])
def geturl():
    session = Session_class()  # 生成session实例 #cursor
    uuid = request.args.get('uuid')
    egfile = session.query(EgFiles).filter(EgFiles.uuid == uuid).first()
    url = egfile.path
    session.close()
    if egfile:
        return json.dumps({'code': 200, 'msg': 'File Path Get Success', 'url': 'http://10.0.225.52/' + url})
    else:
        return json.dumps({'code': 400, 'msg': 'UUID not found'})


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=False)
